package com.tree.common.config.i18n.util;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.util.UrlPathHelper;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @ClassName com.demo.common.i18n.util
 * Description: <类功能描述>. <br>
 * <p>
 * <使用说明>
 * </p>
 * @Author tree
 * @Date 2019-05-26 01:11
 * @Version 1.0
 */
public class WebUtil {
    public static final String SESSION_ID= "session-id";
    public static final String AUTH_TOKEN= "AUTH-token";
    public static final String LANGUAGE_CODE= "language-code";

    public static final String UNKNOWN = "unknown";


    public static String getRemoteAddr(){
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("Http_X_Forwarded_for");

        if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)){
            ip = request.getHeader("X-Forwarded-For");
        }
        if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client_IP");
        }
        if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;

    }

    public static String getRealIp(){
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("X-Real-IP");
        if(StringUtils.isEmpty(ip)){
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    public static String getHeader(String headName){
        String value = getRequest().getHeader(headName);
        return value;
    }

    public static String getLocalHostIp (){
        String ip = "127.0.0.1";
        try {
            InetAddress address = InetAddress.getLocalHost();
            ip = address.getHostAddress().toString();
        }catch (UnknownHostException e){
            e.printStackTrace();
        }
        return  ip;
    }

    public static HttpServletRequest getRequest(){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getPathWithApp(){
        return new UrlPathHelper().getPathWithinApplication(getRequest());
    }



}
